#include "worker.h"
#include "head.h"
int tidArrInit(tidArr_t * tidArr, int workerNum){
    // 申请堆空间内存，保存所有pthread_t
    tidArr->arr = (pthread_t *)calloc(workerNum,sizeof(pthread_t));
    tidArr->workerNum = workerNum;
    return 0;
}
int makeWorker(threadPool_t * pthreadPool){
    // 主线程在创建子线程的时候，干脆把所有信息都传过去
    for(int i = 0; i < pthreadPool->tidArr.workerNum; ++i){
        pthread_create(&pthreadPool->tidArr.arr[i],NULL,
                        threadFunc,pthreadPool);
    }
}
void *threadFunc(void *arg){
    threadPool_t * pthreadPool = (threadPool_t *)arg;
    while(1){
        // 接收任务
        pthread_mutex_lock(&pthreadPool->mutex); //加锁，打算访问任务队列
        while(pthreadPool->taskQueue.queueSize <= 0){//队列为空
            pthread_cond_wait(&pthreadPool->cond,&pthreadPool->mutex);
        }
        int netfd = getFront(&pthreadPool->taskQueue);
        printf("I am worker. I got a task, netfd = %d\n", netfd);
        deQueue(&pthreadPool->taskQueue);
        pthread_mutex_unlock(&pthreadPool->mutex);//解锁 执行任务的时候，不要带锁
        // 执行任务
        transFile(netfd);
        // 任务做完了
        close(netfd);//子线程close等价于主线程close （和父子进程）
    }
}
